#!/usr/local/bin/php
<?php
	define('ZONE_FILE_PLACE',"/tmp/domains/"); #Full path to where your actual zone files will go.
  define('MASTER_CONFIG_FILE',"/tmp/etc/master.hosts"); # Full path to where your master include file will go. Please look in the README
  define("SLAVE_CONFIG_FILE","/tmp/etc/slave.hosts") ;  # Full path to where the Slave include file will go. 
	define("MASTER_SERVER_IP","70.85.29.101");  #The IP of the master server
  define("BINDER_ROOT","/home/vluther/websites/phpcult/htdocs");  #Actual path to where binder is installed, this is where global.inc.php should be. 

	$sapitype = ''; 
  require_once BINDER_ROOT.'/global.inc.php'; # Set this to where your global.inc.php 
  if($sapitype != "cli") { 
    echo "You attempted to access this script via an unusual way. Aborting for Security reasons\n"; 
    die; 
  }
  require_once INCLUDE_PATH . '/Records.class.php'; 
  require_once INCLUDE_PATH . '/FQDN.class.php'; 
  
  
  $objD = new FQDN(); 
  $record = new DNSRecord(); 

  // First get a list of all the Domains in the database . 
  $arrDoms = $objD->loadAllDomains(); 
  $numdoms = count($arrDoms); # Get the number of domains we found in the list

  echo "We found $numdoms domains in the database \n";

  // Uncomment the following line for debugging purposes.   
  #print_r($arrDoms); 
  
  
    
  if($numdoms > 0) { 
    for($i=0;$i<$numdoms;$i++) {
      $fqdnid = $arrDoms[$i]['fqdnid']; 
      $record->mSetId($fqdnid);
      // Get all records for this domain  
      $arrRecords = $record->mLoadRecords();
      if($arrRecords != 0) { 
       	buildZone($arrRecords,$arrDoms,$i); 
      } 
    }
  }
      
function buildZone($arrRecords,$arrDoms,$i) 
{
			global $db,$objD,$record; 
      $fqdnid = $arrDoms[$i]['fqdnid']; 
      $domain = $arrDoms[$i]['fqdn'] ; 
      $ttl = $arrDoms[$i]['ttl']; 
      $serial = $arrDoms[$i]['serial']; 
      $refresh = $arrDoms[$i]['refresh']; 
      $retry = $arrDoms[$i]['retry']; 
      $expiry = $arrDoms[$i]['expiry']; 
      $minimum = $arrDoms[$i]['minimum']; 
      $mname = $arrDoms[$i]['soa_mname']; 
      $soa_rname = $arrDoms[$i]['soa_rname']; 
      $defaultip = $arrDoms[$i]['defaultip'];
      $soa_rname = ereg_replace("\@",".",DEFAULT_RNAME);   

      $record->mSetId($fqdnid);
      $strNS = $record->loadNameServers();
			$nrecords = count($arrRecords); 
			echo "Now creating $domain \n"; 
       
      $fh = fopen(DEFAULT_BOILER,"r") ; 
      $zonefile = fread($fh,filesize(DEFAULT_BOILER)) ;

      $zonefile = ereg_replace("MINIMUM",$minimum,$zonefile) ;
      $zonefile = ereg_replace("REFRESH",$refresh,$zonefile) ; 
      $zonefile = ereg_replace("MNAME",DEFAULT_MNAME,$zonefile) ;
      $zonefile = ereg_replace("RNAME",$soa_rname,$zonefile) ; 
      $zonefile = ereg_replace("SERIAL",$serial,$zonefile) ; 
      $zonefile = ereg_replace("TIMETOLIVE",$ttl,$zonefile) ; 
      $zonefile = ereg_replace("RETRY",$retry,$zonefile) ; 
      $zonefile = ereg_replace("EXPIRY",$expiry,$zonefile) ; 
      $zonefile = ereg_replace("DEFAULT_IP_ADDRESS",$defaultip,$zonefile) ; 
      $zonefile = ereg_replace("NAME_SERVER_LINE",$strNS,$zonefile) ;
  

      $mxrecordline = makeMXLine($fqdnid); 
      $zonefile = ereg_replace("MX_RECORD_LINE",$mxrecordline,$zonefile) ; 

      // Start The loop of hosts for this individual domain  
      for($c=0;$c<$nrecords; $c++) {
        $rtype = $arrRecords[$c]['rtype']; 
        $priority = $arrRecords[$c]['priority']; 
        $ipaddress = $arrRecords[$c]['hostip'] ; 
        #$hostname = $arrRecords[$c]['hostname']; 
        
        if("MX" == $rtype) {
          /* $record->setMXRecord($ipaddress); 
          $mx = $record->_strIp; 
          // Check to see if the last character in the string is .i
          if(!preg_match('/\.$/',$mx)) {
            $mx = $mx . "."; 
          }
          if($mx == ".") {
            $mx = DEFAULT_MX ; 
          }
          
          $foundmx = "Y";   
          #echo "$domain has an MX record of : $mx FOUND MX = $foundmx\n";   
          $mxrecordline .= "IN $rtype $priority $mx\n\t\t"; 
      #    $zonefile = ereg_replace("MX_RECORD_LINE",$mxrecordline,$zonefile) ; 
*/
          continue; 
        } else {
          $zoneline = ''; 
          if("CNAME" == $arrRecords[$c]['rtype']) {
            $zoneline .= $arrRecords[$c]['hostname'] . "\t\t IN \t" . $rtype . "\t" . $arrRecords[$c]['hostip'] . ".\n";  
          } else {
            $zoneline .= $arrRecords[$c]['hostname'] . "\t\t IN \t" . $rtype . "\t" . $arrRecords[$c]['hostip'] . "\n";  
          }
        }

        // If the Rtype is NS, don't make an line for it, make a real 
        // A record , not this. 
        if($rtype == "NS") {
          continue; 
        }
        // If there is no MX record found, make it the default MX record.
         
        if(!isset($foundmx)) {
          #echo "Setting the default MX for $domain \n"; 
          $mxrecordline = "IN MX 10 " . DEFAULT_MX ."."; 
        }
        
       # $zonefile = ereg_replace("MX_RECORD_LINE",$mxrecordline,$zonefile) ; 
        $zonefile = $zonefile . $zoneline ; 
        
        $zone = ZONE_FILE_PLACE . "$domain";
        $fw = fopen($zone,"w") or die ("Could not open $zone") ; 
        fwrite($fw,$zonefile); 
        fclose($fw); 
       
        $masterhosts = "zone \"$domain\" {
          type master;
          file \"domains/$domain\";
        };\n";
      } // End of For loop 
 
        $mfc = fopen(MASTER_CONFIG_FILE.'.new',"a") or die("Could not open the configuration file\n");  
        fwrite($mfc,$masterhosts);
        fclose($mfc); 
        $master_ip = MASTER_SERVER_IP; 
        $slavehosts = "zone \"$domain\" {
        type slave; 
        masters { $master_ip ; }; 
        file \"domains/$domain\"; 
        }; \n"; 
        
        $sfc = fopen(SLAVE_CONFIG_FILE.'.new',"a") or die("Could not open the configuration file\n");  
        fwrite($sfc,$slavehosts);
        fclose($sfc);
        
        //This will update their Serials for next time and set the zonecreated and new to Y and N. 
        //Eventually these values will be used to determine if or when to write a new zone file for a domain. 

        $newserial = time();  
        $update = "UPDATE fqdn SET fqdn='$domain',serial='$newserial',new='N',zonecreated='Y' WHERE fqdnid='$fqdnid'"; 

        $db->mInsert($update);  

        // If all this is done. Remove the old config files. 
         
        unset($zoneline); 	
      
    } // End of Function 

    
    unlink(MASTER_CONFIG_FILE); 
    unlink(SLAVE_CONFIG_FILE); 
    rename(MASTER_CONFIG_FILE.'.new',MASTER_CONFIG_FILE); 
    rename(SLAVE_CONFIG_FILE.'.new',SLAVE_CONFIG_FILE);
    /* Now Restart Named */
    
    

    // UNCOMMENT THIS LINE ONCE YOUR TESTS ARE DONE. 
    #`rndc reload`; 


function makeMXLine($domain) 
{
   global $db; 
   $sql = "SELECT * from records WHERE rtype='MX' AND fqdnid='$domain'"; 
   $rs = $db->mRun($sql); 
   $num_mx = $db->mGetNumRows();
   if($num_mx > 0) {
     while($row=mysql_fetch_assoc($rs)) {
       $mxserver = $row['hostip']; 
       $priority = $row['priority'];
       if(!preg_match('/\.$/',$mxserver)) {
         $mxserver = $mxserver . "."; 
       }

        
       $mxrecordline .= "IN\tMX\t$priority\t$mxserver\n"; 
     }
   } else {
     $mxrecordline = "IN MX 10 " . DEFAULT_MX .".";
   }
    
     return $mxrecordline; 

}
 
    
?>
